<?php

namespace App\Logic;

use App\Model\Setting;
use App\Model\SettingLog;
use Hyperf\Context\Context;

class AdminSettingLogic
{
    /**
     * 获取配置类别
     * @return array
     */
    public static function listSetting(): array
    {
        $settings = Setting::query()->get()->toArray();
        $data = [];
        foreach ($settings as $set) {
            $set['setting'] = new_json_decode($set['setting']);
            if ($set['setting']['type'] == 'hidden') {
                continue;
            }
            if (!isset($data[$set['groups']])) {
                $data[$set['groups']] = [
                    'id' => $set['groups'],
                    'name' => $set['groups_name'],
                    'settings' => []
                ];
            }
            $data[$set['groups']]['settings'][] = $set;
        }
        return array_values($data);
    }

    /**
     * 保存配置
     * @param $data
     * @return true
     */
    public static function saveSetting($data): true
    {
        $setting = Setting::query()->whereIn('name', array_keys($data))->get(['name', 'value', 'setting'])->toArray();
        if (empty($setting)) {
            return true;
        }
        $opUserId = Context::get('userId');
        $opUserName = Context::get('userName');
        foreach ($setting as $set) {
            if ($set['value'] != $data[$set['name']]) {
                $set['setting'] = new_json_decode($set['setting']);
                Setting::query()->where('name', $set['name'])->update([
                    'value' => $data[$set['name']],
                    'last_time' => time(),
                    'last_userid' => $opUserId,
                    'last_username' => $opUserName,
                ]);
                SettingLog::create([
                    'label' => $set['setting']['label'],
                    'name' => $set['name'],
                    'old_value' => $set['value'],
                    'new_value' => $data[$set['name']],
                    'op_userid' => $opUserId,
                    'op_username' => $opUserName,
                    'op_time' => time()
                ]);
            }
        }
        return true;
    }

    /**
     * 配置日志
     * @param $input
     * @return array
     */
    public static function logSetting($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = SettingLog::query()->when(!empty($input['query']['name']), function ($query) use ($input) {
            $query->where('name', $input['query']['name']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }
}